<?php
namespace app\qihan\admin;
use app\admin\controller\Admin;
use app\qihan\model\QihanMaster;
use app\qihan\model\QihanRegion;
use think\Db;
class Master extends QihanBase
{
	//列表页
    public function index()
    {
        if ($this->request->isAjax()) {
            $where = $data = [];
            $page = input('param.page/d', 1);
            $limit = input('param.limit/d', 50);
            $region_id = input('param.region_id/d');
            if ($region_id) {
                $where['region_id'] = $region_id;
            }
            $keyword = input('param.keyword/s');
            if ($keyword) {
                $where['name'] = ['like', "%{$keyword}%"];
            }
            $data['data'] = QihanMaster::with('region')->where($where)->page($page)->limit($limit)->order('ctime desc')->select();
            $data['count'] = QihanMaster::where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        return $this->fetch();
    }
    //添加页
    public function edit()
    {
    	$id = input('param.id/d', 0);
        if ($this->request->isPost()) {
            $mod = new QihanMaster();
            if (!$mod->storage()) {
                return $this->error($mod->getError());
            }
            return $this->success('保存成功');
        }
        $region_id = -1;
        if($id){
        	$row = QihanMaster::where('id', $id)->find();
        	if(!$row){
        		return $this->error('数据不存在');
        	}
            $row['des'] = htmlspecialchars_decode($row['des']);
            $region_id = $row['region_id'];
        	$this->assign('data_info', $row);
        }
        $regions = QihanRegion::select();
        $this->assign('regions',  $this->getSelect($regions,$region_id));
        return $this->fetch('form');
    }
    //删除
    public function del()
    {
        $ids = input('param.id/a');
        $model = new QihanMaster();
        if ($model->del($ids)) {
            return $this->success('删除成功。');
        }
        return $this->error($model->getError());
    }
    //校区下拉
    private function getSelect($data = [], $id = 0)
    {
        if (!$data) {
            return '';
        }
        $str = '';
        foreach ($data as $k => $v) {
            if ($id == $v['id']) {
                $str .= '<option value="'.$v['id'].'" selected>'.$v['name'].'</option>';
            } else {
                $str .= '<option value="'.$v['id'].'">'.$v['name'].'</option>';
            }
        }
        return $str;
    }
}